package com.linkage.jz.bankruptcy.activity.Vote;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.Vote.ProVoteVotersGroupsAdapter;
import com.linkage.jz.bankruptcy.utils.ScreenUtils;
import com.linkage.seapeak.activity.vote.CreditorMultiSelectActivity;
import com.linkage.seapeak.activity.vote.VoteTurnMoneyActivity;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.net.ResultCallBack;
import com.linkage.seapeak.net.VoteNetRequest;
import com.linkage.seapeak.pojo.CrediterUser;
import com.linkage.seapeak.pojo.VoteGroup;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 新建选择表决成员 有分组
 * 返回值为 List<VoteGroup> 对应键名为 result
 */
public class ProVoteVotersGroupsActivity extends BaseWhiteActivity {

    private static final int REQUEST_CODE_MEMBER = 0xf1;
    private static final int REQUEST_CODE_MONEY = 0xf2;
    private String projectId;

    private AYSwipeRecyclerView mRecyclerView;
    private RelativeLayout emptyView;
    private View bottomLay;
    private ProVoteVotersGroupsAdapter mDataAdapter;

    private ArrayList<VoteGroup> mData;
    private List<Object> setData;

    private View addGroupView;
    private PopupWindow addNewGroupPop;

    private int mDataAddIndex = 0;
    private int moneyIndex = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pro_vote_voters_group, "表决人员（0人）");
        projectId = getIntent().getStringExtra("projectId");
        init();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_MEMBER && resultCode == RESULT_OK && data != null) {
            ArrayList<CrediterUser> userList = (ArrayList<CrediterUser>) data.getSerializableExtra("userList");
            for (Object item : setData) {
                if (item instanceof CrediterUser) {
                    for (int i = 0;i < userList.size();i++){
                        if (userList.get(i).getCreditorid().equals(((CrediterUser) item).getCreditorid())) {
                            userList.remove(i);
                            break;
                        }
                    }
                }
            }
            if (mData.get(mDataAddIndex).getMembers() == null)
                mData.get(mDataAddIndex).setMembers(userList);
            else
                mData.get(mDataAddIndex).getMembers().addAll(userList);
            mData.get(mDataAddIndex).setMemberCount(mData.get(mDataAddIndex).getMembers().size());
            notifyDataChanged();
        } else if (requestCode == REQUEST_CODE_MONEY && resultCode == RESULT_OK && data != null){
            CrediterUser user = (CrediterUser) setData.get(moneyIndex);
            user.setVoteMoney(data.getDoubleExtra("money", 0d));
            notifyDataChanged();
        }
    }

    public void init() {
        addGroupView = LayoutInflater.from(ProVoteVotersGroupsActivity.this)
                .inflate(R.layout.pro_vote_add_group_dialog, null, false);
        mRecyclerView = findViewById(R.id.list);
        emptyView = findViewById(R.id.empty);
        bottomLay = findViewById(R.id.bottom_lay);

        mData = new ArrayList<>();
        setData = new ArrayList<>();
        mDataAdapter = new ProVoteVotersGroupsAdapter(this, setData);
        mRecyclerView.setMode(AYSwipeRecyclerView.SwipeType.DISABLE);
        mRecyclerView.setShowEmpty(false);
        mRecyclerView.setAdapter(mDataAdapter);
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddPop(null);
            }
        });

        mDataAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, RecyclerView.ViewHolder viewHolder) {
                VoteGroup item;
                Intent intent;
                switch (v.getId()) {
                    case R.id.item_group_root:
                        item = (VoteGroup) setData.get(position);
                        item.isExpand = !item.isExpand;
                        break;
                    case R.id.item_add:
                        item = (VoteGroup) setData.get(position);
                        mDataAddIndex = mData.indexOf(item);
                        List<String> ids = new ArrayList<>();
                        for (Object user : setData){
                            if (user instanceof CrediterUser)
                                ids.add(((CrediterUser) user).getCreditorid());
                        }
                        intent = new Intent(ProVoteVotersGroupsActivity.this, CreditorMultiSelectActivity.class);
                        intent.putExtra("projectId", projectId);
                        intent.putExtra("type", "2");
                        intent.putExtra("alreadySelectIds", (Serializable) ids);
                        intent.putExtra("canSelectAlready", false);
                        startActivityForResult(intent, REQUEST_CODE_MEMBER);
                        break;
                    case R.id.btn_group_edit:
                        item = (VoteGroup) setData.get(position);
                        showAddPop(item);
                        break;
                    case R.id.btn_group_delete:
                        item = (VoteGroup) setData.get(position);
                        mData.remove(item);
                        break;
                    case R.id.voter_change:
                        moneyIndex = position;
                        intent = new Intent(ProVoteVotersGroupsActivity.this, VoteTurnMoneyActivity.class);
                        intent.putExtra("money", ((CrediterUser) setData.get(moneyIndex)).getVoteMoney());
                        startActivityForResult(intent, REQUEST_CODE_MONEY);
                        break;
                    case R.id.btnDelete:
                        CrediterUser user = (CrediterUser) setData.get(position);
                        for(int i = position;i >= 0;i--) {
                            if (setData.get(i) instanceof VoteGroup) {
                                VoteGroup temp = ((VoteGroup) setData.get(i));
                                temp.setMemberCount(temp.getMemberCount() - 1);
                                temp.getMembers().remove(user);
                            }
                        }
                        break;
                }
                notifyDataChanged();
            }
        });

        addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent();
                    intent.putExtra("result", (Serializable) mData);
                    setResult(RESULT_OK, intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                finish();
            }
        }, "完成", 0));
        findViewById(R.id.add_group).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddPop(null);
            }
        });
        findViewById(R.id.create_ids).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 设置群组编号
                 */
                VoteNetRequest.getGroupMeetingNumber(getUserToken(), (List<VoteGroup>) mData, new ResultCallBack<JsonArray>() {
                    @Override
                    public void onSuccess(JsonArray result) {
                        Log.i(TAG, "getGroupMeetingNumber onSuccess: " + result.toString());
                        for (int i = 0;i < result.size();i++){
                            JsonObject jsonObject = result.get(i).getAsJsonObject();
                            JsonArray array = jsonObject.getAsJsonArray("members");
                            for (int j = 0;j < array.size();j++){
                                JsonObject itemJson = array.get(j).getAsJsonObject();
                                String mId = itemJson.get("creditorId").getAsString();
                                for(int k = 0;k < mData.get(i).getMembers().size();k++) {
                                    String targetId = mData.get(i).getMembers().get(k).getCreditorid();
                                    if (mId.equals(targetId)) {
                                        int meetingNumber = itemJson.get("meetingNumber").getAsInt();
                                        mData.get(i).getMembers().get(k).setMeetingNumber(meetingNumber);
                                        continue;
                                    }
                                }
                            }
                        }
                        hideProgress();
                        notifyDataChanged();
                    }

                    @Override
                    public void onFailed(String msg) {
                        showToast(msg);
                        hideProgress();
                    }
                });
            }
        });
    }

    /**
     * 重新计算，刷新
     */
    public void notifyDataChanged() {
        setData.clear();
        int count = 0;
        if (mData != null && mData.size() > 0) {
            for (VoteGroup group : mData) {
                setData.add(group);
                if (group != null && group.getMembers() != null && group.getMembers().size() > 0
                        && group.isExpand) {
                    count += group.getMemberCount();
                    for (CrediterUser user : group.getMembers())
                        setData.add(user);
                }
            }
        }
        setTitle(count == 0 ? "表决人员（0人）" : "表决人员(" + count + "人)");
        mDataAdapter.notifyDataSetChanged();
        emptyView.setVisibility(mData.size() == 0 ? View.VISIBLE : View.GONE);
        bottomLay.setVisibility(mData.size() != 0 ? View.VISIBLE : View.GONE);
    }

    /**
     * 展示弹窗
     *
     * @param voteGroup
     */
    private void showAddPop(final VoteGroup voteGroup) {
        Button cancelButton = addGroupView.findViewById(R.id.btn_chancel_u);
        Button okButton = addGroupView.findViewById(R.id.btn_save_u);
        TextView title = addGroupView.findViewById(R.id.notice_title);
        final EditText nameEdit = addGroupView.findViewById(R.id.group_name_edit);
        final CheckBox checkCommon = (CheckBox) addGroupView.findViewById(R.id.check_common);
        final CheckBox checkDanbao = (CheckBox) addGroupView.findViewById(R.id.check_danbao);
        final CheckBox checkOther = (CheckBox) addGroupView.findViewById(R.id.check_other);
        nameEdit.setText(voteGroup == null ? "" : voteGroup.getName());
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addNewGroupPop != null && addNewGroupPop.isShowing()) {
                    addNewGroupPop.dismiss();
                }
            }
        });
        title.setText(voteGroup == null ? "新建表决组" : "编辑表决组");


            okButton.setText("确定");


        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (nameEdit.getText().length() == 0) {
                    showToast("名称不可以为空");
                    return;
                }

                if (voteGroup == null) {
                    VoteGroup item = new VoteGroup();
                    item.setName(nameEdit.getText().toString());
                    item.setOrdinary(checkCommon.isChecked());
                    item.setGuarantee(checkDanbao.isChecked());
                    item.setOther(checkOther.isChecked());
                    mData.add(item);
                } else {
                    voteGroup.setName(nameEdit.getText().toString());
                    voteGroup.setOrdinary(checkCommon.isChecked());
                    voteGroup.setGuarantee(checkDanbao.isChecked());
                    voteGroup.setOther(checkOther.isChecked());
                }

                notifyDataChanged();
                if (addNewGroupPop != null && addNewGroupPop.isShowing()) {
                    addNewGroupPop.dismiss();
                }
            }
        });
        if (addNewGroupPop == null || !addNewGroupPop.isShowing()) {
            addNewGroupPop = new PopupWindow(addGroupView, ScreenUtils.getScreenWidth(ProVoteVotersGroupsActivity.this) - 200, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            //产生背景变暗效果
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 0.4f;
            getWindow().setAttributes(lp);
            //点击外面popupWindow消失
            addNewGroupPop.setOutsideTouchable(true);
            //popupWindow获取焦点
            addNewGroupPop.setFocusable(true);
            //popupWindow设置背景图
            addNewGroupPop.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.pro_vote_gray_light)));
            //popupWindow设置开场动画风格
            //popupWindow.setAnimationStyle(R.style.popupWindow_anim);
            //刷新popupWindow
            //popupWindow.update();

            //设置popupWindow消失时的监听
            addNewGroupPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                //在dismiss中恢复透明度
                public void onDismiss() {
                    WindowManager.LayoutParams lp = getWindow().getAttributes();
                    lp.alpha = 1f;
                    getWindow().setAttributes(lp);
                }
            });
            addNewGroupPop.showAtLocation(emptyView.getRootView(), Gravity.CENTER, 0, 0);
        } else {
            //如果popupWindow正在显示，接下来隐藏
            if (addNewGroupPop.isShowing()) {
                addNewGroupPop.dismiss();
            } else {
                //产生背景变暗效果
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 0.4f;
                getWindow().setAttributes(lp);
                addNewGroupPop.showAtLocation(emptyView.getRootView(), Gravity.CENTER, 0, 0);
            }
        }
    }
}
